"""
Launch django application as a service
Requires Mark Hammond's pywin32 package.
"""

import win32serviceutil
import win32service
import win32event
import sys
import  os
_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(_dir, '..'))

class DjangoService(win32serviceutil.ServiceFramework):
    """NT Service."""
    
    _svc_name_ = "DjangoService"
    _svc_display_name_ = "Django Service"
    _exe_name_ = 'pythonservice.exe'
    
    def __init__(self, args):

        win32serviceutil.ServiceFramework.__init__(self, args)
        # create an event that SvcDoRun can wait on and SvcStop
        # can set.
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)

    def SvcDoRun(self):
        from django.core.management import execute_manager
        try:
            import settings # Assumed to be in the same directory.
        except ImportError:
            import sys
            sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
            sys.exit(1)
        execute_manager(settings, ['','runserver','--noreload', '0.0.0.0:8002'])
        # now, block until our event is set...
        win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
    
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

        win32event.SetEvent(self.stop_event)

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(DjangoService)
